import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入路由组件
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'

import Welcome from '../views/Welcome.vue'
import Users from '../views/Users/Users.vue'
import Rights from '../views/Power/Rights.vue'
import Roles from '../views/Power/Roles.vue'
import Category from '@/views/goods/Category.vue'
import Params from '@/views/goods/Params.vue'
import List from '@/views/goods/List.vue'
import AddGoods from '@/views/goods/AddGoods.vue'
import OrderList from '@/views/order/OrderList.vue'
import Reports from '@/views/Reports/Reports.vue'

Vue.use(VueRouter)

const routes = [
  // 配置路由重定向
  { path: '/', redirect: '/login' },
  // 配置登录路由规则
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Category },
      { path: '/params', component: Params },
      { path: '/goods', component: List },
      { path: '/goods/addgoods', component: AddGoods },
      { path: '/orders', component: OrderList },
      { path: '/reports', component: Reports }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // to -- 要跳转的地址
  // from -- 从那个网页跳转过来
  // next -- 方形，执行下一步操作

  // 如果用户访问的是登录页面，那么直接放行，让用户访问登录页面
  if (to.path === '/login') return next()

  // 获取 token ，如果 token 的值是 null ，说明用户没有登录，否则用户处在登录状态
  const myToken = window.sessionStorage.getItem('token')

  // 根据获得的 token 值做出判断
  // 如果不存在 token ,返回的是 null
  // 如果是 null ,说明用户没有登录,这时候取反操作,让路由直接跳到登录页面
  if (!myToken) return next('/login')
  // 如果 token 存在,放行
  next()
})

export default router
